package com.alibaba.dubbo.common.inet.ipv4;

import java.net.InetAddress;
import java.net.InetSocketAddress;

import com.alibaba.dubbo.common.inet.IPMatcherException;
import com.alibaba.dubbo.common.inet.InetAddressMatcher;
import com.alibaba.dubbo.common.inet.InetAddressSupport;



/**
 * ipv4地址相等
 * 
 * @author kingbo.ruan 2014.09.24
 *
 */
public class EqMatcher implements InetAddressMatcher {
	Integer s[][] = new Integer[4][2];
	public EqMatcher(String addr) {
		
		if(addr == null || addr.length() == 0) throw new IPMatcherException();
		for(int i = 0;i < 4;i++){
			s[i] = new Integer[2];
			s[i][0] = 0;
			s[i][1] = 255;
		}
		addr = addr.trim();
		String [] ss = addr.split("\\.");
		if(ss.length > 4) throw new IPMatcherException();
		for(int i = 0;i< ss.length;i++){
			String n = ss[i].trim();
			if(n.length() == 0) continue;
			if(n.equals("*")) continue;
			Integer t = Integer.parseInt(n, 10);
			if(t < 0 || t > 255)  throw new IPMatcherException();
			s[i][0] = t;
			s[i][1] = t;
		}
	}
	
	@Override
	public boolean match(InetAddress address) {
		byte[] addr = address.getAddress();
		for(int i = 0;i < addr.length;i++){
			int b = addr[i];
			if(b < 0) b += 256;
			if(b < s[i][0] || b > s[i][1]) return false;
		}
		return true;
	}

	@Override
	public InetAddress select(InetAddress[] addresses) {
		for(InetAddress address : addresses){
			if(this.match(address)) return address;
		}
		return null;
	}
}
